<template>
  <div id="myStartApproval">
    <div class="tab-panel">
      <van-pull-refresh v-model="isLoading" @refresh="pullRefresh">
        <img
          slot="loading"
          class="loading-gif-refresh"
          src="../../assets/loading.gif"
        >
        <form>
          <div class="search-area-title">
            <van-row type="flex" justify="space-between">
              <van-col span="21">
                <van-search
                  :show-action="showCancel"
                  v-model="searchValue"
                  placeholder="请输入搜索标题"
                  @search="onSearch"
                  @cancel="onCancel"
                />
              </van-col>
              <van-col span="3" class="align-center">
                <img @click="filtratePopup = true" class="search-img" :src="showFiltrateData.length > 0?require('../../assets/documents/shaixuan_active.png'):require('../../assets/documents/shaixuan.png')">
              </van-col>
            </van-row>
          </div>
          <div v-if="showFiltrateData.length > 0" class="filtershow ">
            <p class="van-ellipsis">
              <span>筛选：</span>
              <span class="filter-span" v-for="(item, index) in showFiltrateData" :key="index">
                {{item.title}}
              </span>
            </p>
            <img class="filter-x" @click="filtrateCancel" src="../../assets/documents/filterDelete.png">
          </div>
        </form>
        <template v-if="initiateList.length == 0">
          <div class="no-data-img">
            <img src="../../assets/meeting/no-data.png">
            <p>暂无相关数据</p>
          </div>
        </template>
      <van-list
        v-if="initiateList.length > 0"
        v-model="loading"
        :finished="initiateFinished"
        finished-text="没有更多了"
        @load="onload"
      >
      <van-card v-for="(item,index) in initiateList" :key="`${index}list`" 
        @click="toDetail(item.id, item.types, item.flow, item.uid)">
          <div slot="thumb">
            <template v-if="item.img">
              <van-image radius="4px" class="head-img" :src="`${$common.filePath}${item.img}`" />
            </template>
            <template v-else>
              <img class="head-img" src="../../assets/notification/cell_head.png">
            </template>
          </div>
          <div slot="title">
            <p class="title-class van-ellipsis">{{ item.username }} - {{ item.typename }}</p>
          </div>
          <div slot="desc">
            <p class="desc-info-class van-ellipsis">标题：{{ item.title }}</p>
            <!-- <p class="desc-info-class">流水号：{{ item.number }}</p> -->
            <p class="desc-info-class van-ellipsis">时间：{{ item.date }}</p>
            <!-- personnel_type 
              1://会签
              2://委托
              3://挂起
              4://撤销
              0://没有任何操作  显示步骤名 -->
            <template v-if="item.personnel_type == '0'">
              <p class="desc-box-class" :class="getTypeclass(item.personnel_type)">
                <van-row :span="24" class="van-ellipsis">
                  {{item.flow?item.flow.flowname: ''}} {{item.list? item.list.name : ''}} 
                {{getTypename(item.personnel_type)}}</van-row>
              </p>
            </template>
            <template v-if="item.personnel_type == '1'">
              <p class="desc-box-class van-ellipsis" :class="getTypeclass(item.personnel_type)">
                已转交他人会签
              </p>
            </template>
            <template v-if="item.personnel_type == '2'">
              <p class="desc-box-class van-ellipsis" :class="getTypeclass(item.personnel_type)">
                已委托他人办理
              </p>
            </template>
            <template v-if="item.personnel_type == '3'">
              <p class="desc-box-class van-ellipsis" :class="getTypeclass(item.personnel_type)">
                已挂起
              </p>
            </template>
            <template v-if="item.personnel_type == '4'">
              <p class="desc-box-class recover-flex" :class="getTypeclass(item.personnel_type)">
                流程被撤销
              <van-button type="danger" size="mini" @click.stop="recoverDelete(item.id)">删除</van-button>
              </p>
            </template>
          </div>
        </van-card>
      </van-list>
      </van-pull-refresh>
    </div>

    <!-- 筛选弹出框 -->
    <van-popup v-model="filtratePopup" round lock-scroll position="bottom" class="filtrete-pop"
    @click-overlay="filtrateClose">
      <van-nav-bar title="筛选" class="filtrate-title"/>
      <div class="filtrate-content">
        <van-checkbox-group v-model="filtrateResult" @change="onclick">
          <div v-for="(item,index) in filtrateTree" :key="index" v-if="item.son.length > 0">
            <p class="filtrate-content-title">{{item.typename}}</p>
            <van-row>
              <van-col span="11" v-for="(son, sindex) in item.son" :key="sindex+'son'" :offset="sindex%2==1?'2':''">
                <van-checkbox :ref="`filtrateItem${index}${sindex}`" class="filtrate-choose" :name="son.tplid">{{son.title}}</van-checkbox>
              </van-col>
            </van-row>
          </div>
        </van-checkbox-group>
      </div>
      <van-row type="flex" justify="space-between" class="filtrate-button">
        <van-col span="12">
          <div class="default-class" @click="filtrateCancel">重 置</div>
        </van-col>
        <van-col span="12">
          <div class="info-class" @click="filtrateChose">确 定</div>
        </van-col>
      </van-row>
    </van-popup>
  </div>
</template>
<script type="text/javascript">
  export default {
    data() {
      return {
        isLoading: false,
        loading: false,
        // 发起的
        initiatePage: 1,
        initiateList: [],
        initiateFinished: false,

        searchValue:'',
        showCancel: false,

        fresh: "", //删除流程返回的字段，判断需要刷新数据不

        filtrateTree: [],
        filtratePopup: false, //筛选弹出框控制器
        filtrateResult: [],
        showFiltrateData: [], 
      }
    },
    activated(){
      this.filtrateTree = []
      this.filtratePopup = false, //筛选弹出框控制器
      this.$bridge.callHandler('navTitle', {title: '我的审批'})
      this.getListData( true, true)
      this.getFiltrateData()
    },
    watch: {
      'fresh': {
        handler(newV, oldV){
          if (newV == 'fresh') {
            // console.log(newV)
          }
        }
      },
      /**
       * 筛选框
       */
      'filtratePopup': {
        handler(newV, oldV){
          if (this.filtratePopup) {
            this.$bridge.callHandler('navKeepView')
            this.filtrateTree.forEach((tree,index) => {
              tree.son.forEach((son,sonindex) => {
                this.showFiltrateData.forEach((filtrate, findex) => {
                  if (son.tplid == filtrate.tplid) {
                    this.$refs['filtrateItem' + index +  sonindex][0].$el.classList.add("filtrate-choose_active")
                  }
                })
              })
            })
          } else {
            this.$bridge.callHandler('cancelNavKeepView')
          }
        }
      }
    },
    methods: {
      /**
       * 下拉
       * @return {[type]} [description]
       */
      pullRefresh () {
        setTimeout(_ => {
          this.getListData(true, false)
        },500)
      },
      /**
       * 上拉
       * @return {[type]} [description]
       */
      onload () {
        this.getListData(false, false)
      },
      /**
       * 获取列表数据
       * @return {[type]} [description]
       */
      getListData(init, showToast) {
        let self = this
        let tplids = []
        tplids = self.showFiltrateData.map(item => {
          return item.tplid
        })
        if(init) {
          self.initiatePage = 1;
          self.initiateFinished = false;
        }
        let config = {
          method: "POST",
          url: `${self.$common.basePath}aatp5/public/index.php/workclass/work_class/index`,
          data: {
            page: self.initiatePage++ ,
            user_id: self.$store.state.userId,
            title: self.searchValue,
            tplid: tplids
          }
        }
        if(showToast) {
          self.$toast({
            duration: 0,
            forbidClick: true,
            className: 'loading-toast',
            icon: require('../../assets/loading.gif'),
          })
        }
        if(!self.initiateFinished || init) {
          self.$axios(config).then(res => {
            self.loading = false
            self.initiateList = init?res.data.data : self.initiateList.concat(res.data.data)
            if(self.initiateList.length >= res.data.count) {
              self.initiateFinished = true 
            }
            self.isLoading = false
            self.$toast.clear()
          }).catch(err => {
            self.$toast.clear()
            self.initiateFinished = true 
            self.initiateList = []
            self.loading = false
          })
        }
      },
      getDataFiled(dataFiled) {
        return this[dataFiled]
      },
      /**
       * 搜索栏
       * @param  {[type]} type [description]
       * @return {[type]}      [description]
       */
      onSearch (value) {
        if (value) {
          this.showCancel = true
        }
        this.getListData(true, true)
      },
      /**
       * 取消搜索
       * @return {[type]} [description]
       */
      onCancel () {
        this.showCancel = false
        this.getListData(true, true)
      },
      /*
        * 获取筛选数据
       */
      getFiltrateData() {
        let config = {
          method: "post",
          url: `${this.$common.basePath}workclass.php`,
          data: {
            do: "workaddlist",
            user_id: this.$store.state.userId
          }
        }
        this.$axios(config).then(res => {
          this.filtrateTree = res.data
        }).catch(err => {
          this.$toast(err.msg)
        })
      },
      /**
       * 选择事件
       * @return {[type]} [description]
       */
      onclick(e) {
        let self = this
        // 给元素动态添加class
        self.filtrateTree.forEach((tree,index) => {
          tree.son.forEach((son,sonindex) => {
            if (self.$refs['filtrateItem' + index + sonindex][0].checked) {
              // console.log(1)
              self.$refs['filtrateItem' + index +  sonindex][0].$el.classList.add("filtrate-choose_active")
            } else {
              // console.log(2)
              self.$refs['filtrateItem' + index +  sonindex][0].$el.classList.remove("filtrate-choose_active")
            }
          })
        })
      },
      /**
       * 点击蒙层关闭筛选框
       * @return {[type]} [description]
       */
      filtrateClose() {
        let self = this
        // 给元素动态重置class
        self.filtrateTree.forEach((tree,index) => {
          tree.son.forEach((son,sonindex) => {
            if (self.$refs['filtrateItem' + index + sonindex][0].checked) {
              self.$refs['filtrateItem' + index +  sonindex][0].$el.classList.remove("filtrate-choose_active")
            }
            self.showFiltrateData.forEach((filtrate, findex) => {
              if (son.tplid == filtrate.tplid) {
                self.$refs['filtrateItem' + index +  sonindex][0].$el.classList.add("filtrate-choose_active")
              }
            })
          })
        })
        // 同时将v-model删掉
        self.filtrateResult = self.showFiltrateData.map(item => {
          return item.tplid
        })
      },
      /**
       * 重置
       * @return {[type]} [description]
       */
      filtrateCancel() {
        let self = this
        // 给元素动态添加class
        self.filtrateTree.forEach((tree,index) => {
          tree.son.forEach((son,sonindex) => {
            if (self.$refs['filtrateItem' + index + sonindex][0]) {
              // console.log(1)
              self.$refs['filtrateItem' + index +  sonindex][0].$el.classList.remove("filtrate-choose_active")
            }
          })
        })
        this.filtrateResult = []
        this.showFiltrateData = []
        // this.filtratePopup = false
        this.getListData(true, true)
      },
      /**
       * 筛选
       * @return {[type]} [description]
       */
      filtrateChose() {
        this.filtratePopup = false
        // 筛选条件显示---数据处理
        if (this.filtrateResult.length > 0) {
          // 先清空数据
          this.showFiltrateData = []
            this.filtrateResult.forEach(newItem => {
              this.filtrateTree.forEach(item => {
                item.son.forEach(child => {
                  if (newItem == child.tplid) {
                    this.showFiltrateData.push(child)
                  }
                })
              })
            })
          } else {
            this.showFiltrateData = []
          }
        this.getListData(true, true)
      },
      getTypename(type) {
        let typename = ""
        switch(type) {
          case '0':
            typename = '未审批'
            break;
          case '1':
            typename = '会签'
            break;
          case '2':
            typename = '委托'
            break;
          case '3':
            typename = '挂起'
            break;
          case '4':
            typename = '撤销'
            break;
          default:
            typename = '结束'
        }
        return typename;
      },
      getTypeclass(type) {
        let typeclass = ''
        switch(type) {
          case '0':
            typeclass = 'agreen-class'
            break;
          case '1':
            typeclass = 'close-class'
            break;
          case '2':
            typeclass = 'agreen-class'
            break;
          case '3':
            typeclass = 'defined-class'
            break;
          case '4':
            typeclass = 'revocation-class'
            break;
          default:
            typeclass = 'agreen-class'
        }
        return typeclass;
      },
      /**
       * 点击进去详情页面
       * @param  {[type]} id   [description]
       * @param  {[type]} type [description]
       * @return {[type]}      [description]
       */
      toDetail(id, types, flow, uid) {
          this.$router.push({ name:'approvalInfo', query:{workid: id, type: types, step: flow.flownum, uid: uid} })
      },
      /**
       * 删除
       * @return {[type]} [description]
       */
      recoverDelete (id) {
        this.$bridge.callHandler('navKeepView')
        this.$dialog.confirm({
          title:'警告',
          message: '是否确认删除该流程？'
        }).then(() => {
          this.$bridge.callHandler('cancelNavKeepView')
          let config = {
            method: "post",
            url: `${this.$common.basePath}workclass.php`,
            data: {
              do: "delete",
              user_id: this.$store.state.userId,
              workid: id
            }
          }
          this.$axios(config).then(res => {
            this.$toast.success('删除成功')
            this.getListData(true, true)
          }).catch(err => {
            this.$toast.fail(err.msg)
          })
        }).catch(() => {
          this.$bridge.callHandler('cancelNavKeepView')
        })
      }
    }
  }
</script>
<style type="text/css" lang="less" scoped>
  .tab-panel  {
    -webkit-overflow-scrolling: touch;
    // height: calc(100vh - 94px);
    // overflow-y: auto;
    background: #f5f5f5;
    // padding-top: 53px;
    .van-list {
      // padding-top: 12px;
      min-height: calc(100vh - 110px);
    }
  }
  p{
    margin: 0;
  }
  .head-img {
    width: 40px;
    height: 40px;
    border-radius: 4px;
  }
  .title-class {
    font-size: 17px;
    color: #333333;
    font-weight: bold;
    margin-bottom: 5px;
  }
  .desc-info-class {
    font-size: 14px;
    color: #999999;
    margin-top: 5px;
    margin-bottom: 5px;
  }
  .desc-box-class {
    margin-top: 5px;
    // height: 40px;
    font-size: 14px;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    // padding-left: 10px;
    // padding-right: 10px;
  }
  .margin-l-13 {
    margin-left: 13px;
  }
  // 同意
  .agreen-class {
    // background-color: rgba(46, 121, 255, 0.06);
    color: #2E79FF;
  }
  // 退回
  .defined-class {
    // background-color: rgba(245, 75, 3, 0.06);
    color: rgb(245, 75, 3);
  }
  // 结束
  .close-class {
    // background-color: rgba(1, 191, 101, 0.06);
    color: rgb(1, 191, 101);
  }
  // 撤销
  .revocation-class {
    // background-color: rgba(245, 167, 3, 0.06);
    color: rgb(245, 167, 3);
  }
  .no-data-img {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 40% 0;
    background-color: #f5f5f5;

    img {
      width: 180px;
      height: 106px;
      text-align: center;
    }

    p{
      font-size: 17px;
      color: #333333
    }
  }
  .recover-flex {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
</style>
<style type="text/css" lang="less">
  #myStartApproval {
    -webkit-overflow-scrolling: touch;
    height: calc(100vh - 50px);
    background-color: #f5f5f5;
    position: static;

    .search-area {
      margin-top: 12px;
      .van-cell {
        line-height: 25px;
      }
    }

    .van-tab span {
      font-size: 14px;
    }
    .van-tab {
      flex-basis: 20%!important;
    }
    .van-tabs__wrap {
      padding: 0 15px;
      background-color: #fff;
    }
    .van-tabs__line {
      width: 55.5px!important;
    }
    .van-card {
      background-color: #fff;
      margin-top: 0;
      padding: 15px 15px 0 15px;
    }
    .van-card__thumb {
      width: auto;
      height: auto;
      margin-right: 12px;
    }
    .van-card__content{
      min-height: auto;
      padding-bottom: 15px;
      border-bottom: 1px solid #F5F5F5;
    }
  }
</style>